<template>
  <div class="order-confirm-container">
    <div class="order-header">
      <h2>订单确认</h2>
      <el-steps :active="1" simple>
        <el-step title="选择商品" icon="ShoppingCart" />
        <el-step title="确认订单" icon="Document" />
        <el-step title="支付" icon="Money" />
      </el-steps>
    </div>

    <div class="order-content">
      <!-- 收货地址 -->
      <div class="address-section">
        <div class="section-header">
          <h3>收货地址</h3>
        </div>
        <el-select
          v-model="selectedAddress"
          placeholder="请选择收货地址"
          class="simple-select"
          size="large"
          value-key="addressId"
          @change="handleAddressChange"
        >
          <el-option
            v-for="address in addresses"
            :key="address.addressId"
            :label="addressLabel(address)"
            :value="address"
          >
            <span>{{ address.addressName }} {{ address.addressTelno }}</span>
            <span style="margin-left:10px">{{ address.addressProvince }}{{ address.addressCity }}
              {{ address.addressArea }}{{ address.addressDetail }}</span>
          </el-option>
        </el-select>
        <div v-if="addresses.length === 0" class="no-data-hint">
          <el-button type="text" @click="goToAddressManage">暂无收货地址，去添加</el-button>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="product-section">
        <div class="section-header">
          <h3>商品信息</h3>
        </div>
        <div class="product-list">
          <div class="product-item">
            <img :src="product.productMainImg" class="product-image" />
            <div class="product-info">
              <div class="product-name">{{ product.productName }}</div>
              <div class="product-spec">{{ product.productColor }} / {{ product.productSize }}</div>
            </div>
            <div class="product-price">¥{{ product.productPrice.toFixed(2) }}</div>
            <div class="product-quantity">x1</div>
          </div>
        </div>
      </div>

      <!-- 优惠券选择 -->
      <div class="coupon-section">
        <div class="section-header">
          <h3>优惠券</h3>
        </div>
        <el-select
          v-model="selectedCoupon"
          placeholder="请选择优惠券"
          class="simple-select"
          size="large"
          value-key="mycouponId"
          @change="handleCouponChange"
        >
          <el-option
            v-for="coupon in availableCoupons"
            :key="coupon.mycouponId"
            :label="couponLabel(coupon)"
            :value="coupon"
          >
            <span style="color:red;font-weight:bold">¥{{ coupon.mycouponPrice }}</span>
            <span style="margin-left:10px">{{ coupon.yy }}</span>
          </el-option>
        </el-select>
      </div>

      <!-- 订单备注 -->
      <div class="remark-section">
        <el-input
          v-model="orderRemark"
          type="textarea"
          :rows="2"
          placeholder="请输入订单备注（选填）"
          maxlength="100"
          show-word-limit
          class="elegant-textarea"
        />
      </div>

      <!-- 订单汇总 -->
      <div class="summary-section">
        <div class="summary-row">
          <span>商品总价</span>
          <span>¥{{ product.productPrice.toFixed(2) }}</span>
        </div>
        <div class="summary-row">
          <span>运费</span>
          <span>¥0.00</span>
        </div>
        <div class="summary-row" v-if="selectedCoupon">
          <span>优惠券抵扣</span>
          <span class="discount">-¥{{ selectedCoupon.mycouponPrice.toFixed(2) }}</span>
        </div>
        <div class="summary-row total">
          <span>应付总额</span>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <div class="order-footer">
      <div class="footer-left">
        <span>应付金额：</span>
        <span class="pay-amount">¥{{ totalAmount.toFixed(2) }}</span>
      </div>
      <div class="footer-right">
        <el-button 
          type="primary" 
          @click="submitOrder" 
          :loading="loading"
          :disabled="!selectedAddress"
          class="submit-btn"
        >
          立即支付
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { mycouponsAPI, addressAPI } from '@/http'

interface Coupon {
  couponId: number
  mycouponGetTime: string
  mycouponId: number
  mycouponNumber: string
  mycouponPrice: number
  mycouponStatus: number // 0已使用 1可用 2已过期
  userId: number
  xx: string // 过期时间
  yy: string // 满减条件
}

interface Address {
  addressId: number
  addressName: string
  addressTelno: string
  addressProvince: string
  addressCity: string
  addressArea: string
  addressDetail: string
  addressStatus: number // 1是默认地址
  userId: number
}

const router = useRouter()
const loading = ref(false)
const orderRemark = ref('')
const selectedCoupon = ref<Coupon | null>(null)
const selectedAddress = ref<Address | null>(null)
const coupons = ref<Coupon[]>([])
const addresses = ref<Address[]>([])

// 从路由state获取商品信息
const product = ref({
  id: 0,
  productName: '',
  productPrice: 0,
  productMainImg: '',
  productColor: '',
  productSize: ''
})

// 获取可用优惠券
const availableCoupons = computed(() => {
  return coupons.value.filter(coupon => 
    coupon.mycouponStatus === 1 && 
    product.value.productPrice >= parseMinCondition(coupon.yy))
})

// 计算总金额
const totalAmount = computed(() => {
  let amount = product.value.productPrice
  if (selectedCoupon.value) {
    amount -= selectedCoupon.value.mycouponPrice
  }
  return Math.max(amount, 0) // 确保金额不小于0
})

// 解析最低消费条件
const parseMinCondition = (yy: string) => {
  const matches = yy.match(/满(\d+)减(\d+)/)
  return matches ? parseInt(matches[1]) : 0
}

// 地址显示标签
const addressLabel = (address: Address) => {
  return `${address.addressName} ${address.addressTelno} ${address.addressProvince}${address.addressCity}${address.addressArea}${address.addressDetail}`
}

// 优惠券显示标签
const couponLabel = (coupon: Coupon) => {
  return `¥${coupon.mycouponPrice} (${coupon.yy})`
}

// 处理地址选择变化
const handleAddressChange = (val: Address) => {
  selectedAddress.value = val
}

// 处理优惠券选择变化
const handleCouponChange = (val: Coupon) => {
  selectedCoupon.value = val
}

// 获取优惠券列表
const fetchCoupons = async () => {
  try {
    loading.value = true
    coupons.value = await mycouponsAPI.getProductList()
  } catch (error) {
    ElMessage.error('获取优惠券失败')
  } finally {
    loading.value = false
  }
}

// 获取地址列表
const fetchAddress = async () => {
  try {
    const response = await addressAPI.getAddress()
    addresses.value = response.data
    console.log('addresses', addresses.value)
    
    // 设置默认地址
    const defaultAddress = addresses.value.find(item => item.addressStatus === 1)
    if (defaultAddress) {
      selectedAddress.value = defaultAddress
    } else if (addresses.value.length > 0) {
      selectedAddress.value = addresses.value[0]
    }
  } catch (error) {
    ElMessage.error('获取地址失败')
  }
}

// 跳转地址管理
const goToAddressManage = () => {
  router.push('/user/address')
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  try {
    loading.value = true
    
    const orderData = {
      productId: product.value.id,
      price: product.value.productPrice,
      couponId: selectedCoupon.value?.mycouponId || null,
      remark: orderRemark.value,
      amount: totalAmount.value,
      addressId: selectedAddress.value.addressId
    }
    
    await new Promise(resolve => setTimeout(resolve, 800))
    const orderId = 'FLASH_' + Date.now()
    
    ElMessage.success('订单创建成功，即将跳转支付')
    
    console.log('跳转到支付页面', {
      orderId,
      amount: totalAmount.value
    })
    buyNow()  // 沙箱支付宝支付
    
  } catch (error) {
    ElMessage.error(error.message || '订单提交失败')
  } finally {
    loading.value = false
  }
}

// 沙箱支付宝支付
import { alipayAPI } from '@/http'

const buyNow = async () => {
  try {
    // 直接使用你提供的参数
    const paymentData = {
      subject: product.value.productName,  // 商品名称
      traceNo: `ORDER_${Date.now()}`, // 简单生成订单号
      totalAmount: product.value.productPrice - (selectedCoupon.value?.mycouponPrice || 0),  // 订单金额
    };

    // 调用支付宝接口
    const response = await alipayAPI.getAliPay(paymentData);
    
    // 处理支付页面
    const payWindow = window.open('', '_blank');
    if (payWindow) {
      payWindow.document.write(response);
    } else {
      // 如果弹窗被拦截，直接在当前页面显示
      document.body.innerHTML = response;
    }
    
  } catch (error) {
    console.error('支付失败:', error);
    alert('支付失败，请重试');
  }
};

// 初始化
onMounted(() => {
  const productFromQuery = router.currentRoute.value.query.product
  if (productFromQuery) {
      product.value = JSON.parse(productFromQuery as string)
  } else if (router.currentRoute.value.state?.product) {
      product.value = router.currentRoute.value.state.product
  } else {
      ElMessage.error('商品信息获取失败')
      router.back()
      return
  }

  fetchCoupons()
  fetchAddress()
})
</script>

<style scoped>
.order-confirm-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-header {
  margin-bottom: 30px;
  text-align: center;
}

.order-content {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.section-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.simple-select {
  width: 100%;
  margin-bottom: 20px;
}

.product-list {
  border: 1px solid #eee;
  border-radius: 4px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-spec {
  color: #999;
  font-size: 12px;
}

.product-price {
  width: 120px;
  text-align: center;
  font-weight: bold;
}

.product-quantity {
  width: 80px;
  text-align: center;
}

.elegant-textarea {
  margin-bottom: 20px;
}

.summary-section {
  margin-top: 30px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.summary-row.total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-size: 16px;
  font-weight: bold;
}

.total-amount {
  color: #f56c6c;
  font-size: 18px;
}

.discount {
  color: #67c23a;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.footer-left {
  font-size: 16px;
}

.pay-amount {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.submit-btn {
  padding: 12px 30px;
  font-size: 16px;
}

.no-data-hint {
  text-align: center;
  margin: 20px 0;
}
</style>